// Dashboard 状态管理

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type {
  SalesOverview,
  Contract,
  Project,
  UserConfig,
  AppError,
  TimeRange
} from '@/types'
import { ErrorType } from '@/types'
import { dashboardAPI } from '@/services/dashboard-api'
import { dataCache } from '@/utils/cache'
import { DEFAULT_REFRESH_INTERVAL } from '@/types'

export const useDashboardStore = defineStore('dashboard', () => {
  // ============ 状态 ============
  const salesData = ref<SalesOverview | null>(null)
  const contracts = ref<Contract[]>([])
  const projects = ref<Project[]>([])
  const loading = ref(false)
  const error = ref<AppError | null>(null)
  const lastUpdate = ref<Date | null>(null)

  // 用户配置
  const userConfig = ref<UserConfig>({
    layout: {
      type: 'grid',
      columns: 3,
      gap: 16
    },
    visibleMetrics: ['revenue', 'contracts', 'projects', 'completion'],
    refreshInterval: DEFAULT_REFRESH_INTERVAL,
    theme: {
      name: 'tech-dark'
    },
    chartPreferences: {
      showGrid: true,
      showLegend: true,
      showTooltip: true,
      animationDuration: 750,
      smoothCurves: true
    }
  })

  // 时间范围
  const timeRange = ref<TimeRange>({
    start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30 天前
    end: new Date()
  })

  // 自动刷新定时器
  let refreshTimer: number | null = null
  let updateUnsubscribe: (() => void) | null = null

  // ============ 计算属性 ============
  const hasData = computed(() => salesData.value !== null)
  const isError = computed(() => error.value !== null)
  const activeProjectsCount = computed(() => 
    projects.value.filter(p => p.status === 'in-progress').length
  )
  const delayedProjectsCount = computed(() =>
    projects.value.filter(p => p.status === 'delayed').length
  )

  // ============ Actions ============

  /**
   * 获取所有看板数据
   */
  async function fetchDashboardData(): Promise<void> {
    loading.value = true
    error.value = null

    try {
      // 检查缓存
      const cachedData = dataCache.get<SalesOverview>('salesOverview')
      if (cachedData) {
        salesData.value = cachedData
      } else {
        const response = await dashboardAPI.getSalesOverview()
        if (response.success) {
          salesData.value = response.data
          dataCache.set('salesOverview', response.data, 60000) // 缓存 1 分钟
        } else {
          throw new Error(response.message || 'Failed to fetch sales overview')
        }
      }

      // 获取合同数据
      const contractsResponse = await dashboardAPI.getContracts({ limit: 50 })
      if (contractsResponse.success) {
        contracts.value = contractsResponse.data
      }

      // 获取项目数据
      const projectsResponse = await dashboardAPI.getProjects({ limit: 30 })
      if (projectsResponse.success) {
        projects.value = projectsResponse.data
      }

      lastUpdate.value = new Date()
    } catch (err) {
      error.value = {
        type: ErrorType.API_ERROR,
        message: err instanceof Error ? err.message : 'Unknown error',
        timestamp: new Date(),
        recoverable: true
      }
      console.error('Failed to fetch dashboard data:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 刷新数据
   */
  async function refreshData(): Promise<void> {
    // 清除缓存
    dataCache.clear()
    await fetchDashboardData()
  }

  /**
   * 更新用户配置
   */
  function updateUserConfig(config: Partial<UserConfig>): void {
    userConfig.value = {
      ...userConfig.value,
      ...config
    }
    saveUserConfig()
  }

  /**
   * 保存用户配置到 localStorage
   */
  function saveUserConfig(): void {
    try {
      localStorage.setItem('dashboardConfig', JSON.stringify(userConfig.value))
    } catch (err) {
      console.error('Failed to save user config:', err)
    }
  }

  /**
   * 加载用户配置
   */
  function loadUserConfig(): void {
    try {
      const saved = localStorage.getItem('dashboardConfig')
      if (saved) {
        const parsed = JSON.parse(saved)
        userConfig.value = {
          ...userConfig.value,
          ...parsed
        }
      }
    } catch (err) {
      console.error('Failed to load user config:', err)
    }
  }

  /**
   * 设置时间范围
   */
  function setTimeRange(range: TimeRange): void {
    timeRange.value = range
  }

  /**
   * 清除错误
   */
  function clearError(): void {
    error.value = null
  }

  /**
   * 启动自动刷新
   */
  function startAutoRefresh(): void {
    stopAutoRefresh() // 先停止现有的定时器

    const interval = userConfig.value.refreshInterval
    refreshTimer = window.setInterval(() => {
      refreshData()
    }, interval)

    // 订阅实时更新
    updateUnsubscribe = dashboardAPI.subscribeToUpdates((data) => {
      if (data.type === 'data-update' && data.data.salesOverview) {
        salesData.value = data.data.salesOverview
        lastUpdate.value = new Date()
      }
    })
  }

  /**
   * 停止自动刷新
   */
  function stopAutoRefresh(): void {
    if (refreshTimer !== null) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }

    if (updateUnsubscribe) {
      updateUnsubscribe()
      updateUnsubscribe = null
    }
  }

  /**
   * 重试失败的操作
   */
  async function retry(): Promise<void> {
    clearError()
    await fetchDashboardData()
  }

  // ============ 初始化 ============
  loadUserConfig()

  return {
    // 状态
    salesData,
    contracts,
    projects,
    loading,
    error,
    lastUpdate,
    userConfig,
    timeRange,

    // 计算属性
    hasData,
    isError,
    activeProjectsCount,
    delayedProjectsCount,

    // Actions
    fetchDashboardData,
    refreshData,
    updateUserConfig,
    setTimeRange,
    clearError,
    startAutoRefresh,
    stopAutoRefresh,
    retry
  }
})
